import { Page } from 'puppeteer';
import { I_A } from './_base';
import { TemplateVideoUrl } from './videometa';
import { AT } from './at';

interface _ICursor {
    is_begin: boolean;
    prev: number;
    next: number;
    is_end: boolean;
    pagination_reply: {
        next_offset: string;
    };
    session_id: string;
    mode: number;
    mode_text: string;
    all_count: number;
    support_mode: number[];
    name: string;
}

interface _IMember {
    mid: string;
    uname: string;
    sex: string;
    sign: string;
    avatar: string;
    rank: string;
    face_nft_new: number;
    is_senior_member: number;
    senior: any;
    level_info: any;
    pendant: any;
    nameplate: any;
    official_verify: any;
    vip: any;
}

interface _IContent {
    message: string,
    at_name_to_mid: {
        [key: string]: number;
    },
    at_name_to_mid_str: {
        [key: string]: string;
    },
    members: _IMember[];
    emote: any;
    jump_url: any;
    max_line: number;
    pictures: {
        img_src: string;
        img_width: number;
        img_height: number;
        img_size: number;
    }[];
    picture_scale: number;
}


interface _IReplies {
    rpid: number,
    oid: number,
    type: number,
    mid: number;
    root: number;
    parent: number;
    dialog: number,
    count: number,
    rcount: number,
    state: number,
    fansgrade: number,
    attr: number,
    ctime: number,
    mid_str: string,
    oid_str: string,
    rpid_str: string,
    root_str: string,
    parent_str: string,
    dialog_str: string,
    like: number,
    action: number,
    member: _IMember,
    content: _IContent,
}
// https://api.bilibili.com/x/v2/reply/wbi/main?oid=778925870&type=1&mode=3&pagination_str=%7B%22offset%22:%22%22%7D&plat=1&seek_rpid=&web_location=1315875&w_rid=6df0879dedd5d066f78ad95c2f4b5109&wts=1758014669

export interface INote {
    BVid: string;
    commentId: number;
    note: string;
    noteImages: string[];
}

export class Note implements INote {
    constructor(public BVid: string, public commentId: number, public note: string, public noteImages: string[]) {
    }
}

export async function fetchNote(
    page: Page,
    BV: string,
    commmentId: number
): Promise<Note | null> {
    const targetUrl = `https://api.bilibili.com/x/v2/reply/wbi/main`;
    let OuterTargetNote: Note | null = null;
    page.on('response', async (response) => {
        const url = response.request().url();
        if (url.includes(targetUrl)) {
            const rawData = await response.json() as unknown as I_A<{
                cursor: _ICursor;
                replies: _IReplies[];
            }>;
            const targetNote = rawData.data.replies.find((reply) => reply.rpid === commmentId);
            if (!targetNote) {
                return null;
            }
            try {
                const node = new Note(BV, targetNote.rpid, targetNote.content.message, targetNote.content.pictures.map((picture) => picture.img_src));
                OuterTargetNote = node;
            } catch (error) {
                const node = new Note(BV, targetNote.rpid, targetNote.content.message, []);
                OuterTargetNote = node;
            }           
        }
    });

    await page.goto(TemplateVideoUrl(BV) + `#reply${commmentId}`);
    await new Promise(resolve => setTimeout(resolve, 10000));
    return OuterTargetNote;
}


export async function fetchNoteWithAt(
    page: Page,
    at: AT
): Promise<{
    at: AT;
    note: Note;
} | null> {
    const note = await fetchNote(page, at.BV(), at.commentId());
    if (!note) {
        return null;
    } else {
        return {
            at,
            note,
        };
    }
}